package com.ellecity06.debugtools.ui.fragment.request

import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.ellecity06.debugtools.databinding.DebugItemRequestListBinding
import com.ellecity06.debugtools.db.entity.RequestEntity
import com.ellecity06.debugtools.utils.TimeUtils
import com.ellecity06.debugtools.utils.UnitUtils

/**
 * @author ellecity06
 * @time 2023/4/20 11:12
 * @des
 */
internal class DebugRequestListAdapter(private val onClick: ((position: Int, item: RequestEntity) -> Unit)? = null) :
    PagingDataAdapter<RequestEntity, DebugRequestListAdapter.ViewHolder>(DIFF_CALLBACK) {
    companion object {
        val DIFF_CALLBACK = object : DiffUtil.ItemCallback<RequestEntity>() {
            override fun areItemsTheSame(oldItem: RequestEntity, newItem: RequestEntity): Boolean =
                oldItem.id == newItem.id

            override fun areContentsTheSame(oldItem: RequestEntity, newItem: RequestEntity): Boolean =
                oldItem == newItem

            override fun getChangePayload(oldItem: RequestEntity, newItem: RequestEntity): Any? {
                return super.getChangePayload(oldItem, newItem)
            }
        }
    }


    inner class ViewHolder(val binding: DebugItemRequestListBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position) ?: return
        holder.binding.apply {
            tvCode.text = item.code.toString()
            tvCode.setTextColor(if (item.code == 200L) Color.GREEN else Color.RED)
            tvContentLength.text = UnitUtils.fileSize(if (item.contentLength != null) (item.contentLength ?: 0).toDouble() else 0.00)
            tvMethod.text = item.method
            tvStartTime.text = TimeUtils.getDate("yyyy-MM-dd HH:mm:ss:SSS", item.sentRequestAtMillis ?: 0)
            tvTimeConsuming.text = UnitUtils.timeUnit((item.receivedResponseAtMillis ?: 0) - (item.sentRequestAtMillis ?: 0))
            tvHost.text = item.host
            tvPath.text = item.path
            tvError.visibility = if (item.errorMessage == null || item.errorMessage!!.isEmpty()) View.GONE else View.VISIBLE
            if (onClick != null) {
                root.setOnClickListener {
                    onClick.invoke(position, item)
                }
            }

        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(DebugItemRequestListBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }
}